Creating a Calculator in Python: A Beginner’s Guide
Photo by Chris Ried on Unsplash

Building a calculator is the second step above the classic “Hello World!” program. It is a way of mastering all of the essentials like printing, input, and if-else statements. In this step-by-step tutorial, we will look in the process of designing and implenting a simple calculator program in Python.

Prerequisites

No prior knowledge of Python is required However, you’ll need a working version of Python installed on your computer. If you haven’t installed Python yet, or something is not working properly, don’t be discouraged! You can use an online Python editor such as Online Python Editor. These tools simplify the setup process, allowing you to focus on learning. If you are using an online tool, jump to the “The Structure of the Calculator” Section

Setting up the Project

Before we create our calculator, let’s set up the project.

  • Create a Project Folder: Start by creating a new folder named “Calculator Project” on your computer.
  • Create a Python File: Inside the “Calculator Project” folder, create a new file named calculator.py.
  • Open the File in Your Editor: Open the calculator.py file in your favorite text editor or Integrated Development Environment (IDE).

Writing the Initial Code:

print("Hello World")

Then in your terminal type python calculator.py . It should print out “Hello World” in the terminal.

If it doesn’t work, there are a few things you need to look at:

Are you in the right directory?

In windows, it looks like C:\Users\Your-Name\... . At the end, it should say Calculator. If it does not, then you have to get to the right directory. Look at how to do this: https://www.lifewire.com/change-directories-in-command-prompt-5185508

In Mac, it looks like user@User's-MacBook-… or something similar. After your macbook model, it should say Calculator . Example: user@User's-MacBook-Air Calculator . If it does not, then you need to get to the right directory. Look at how to do this: https://support.apple.com/en-gb/guide/mac-help/mchlp1236/mac

Is Python Working?

Just open your terminal and type in python it should look something like this:

Python 3.11.5 (main, Sep 11 2023, 08:31:25) [Clang 14.0.6 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

If it does look like this, Python is working properly. Type in exit() . Python is working in your machine and the program should work.

It you get Python:command not found then python is not installed or working properly in your system. Check out how to set-up Python

Note: In older Macs, Python 2.7 comes preinstalled, you might need to type in python3 instead of python

If this works for you, you’re ready to create the calculator!

The Structure of the Calculator

Our calculator will have 3 parts:

  • Input: Getting the numbers and the desired operation from the User
  • Calculator logic: Computing the answer from the input numbers
  • Output: Outputing the result from the calcaultion

Let’s dive into each of the steps

Input

Python uses the input() function to get the input from the user.

First we prompt the user to enter something and then we record what the user entered into a variable.

What are variables?

Think of a variable as a named container. You’re storing information in some place in the computer’s memory, and then giving it a name so that in the future you can referencing that information through the name.

This is what the code would look like:

user_input = input('Enter a number: ')

user_input is the name of the variable we have created. And the value that will be stored under that name is whatever we get from the input() function. And the message in the function is just what the user sees when they run the command.

What are strings?

Notice that the message is sorrounded by '' quotation marks. These quotation marks tell Python that whatever you’re entering in them is a sentence. Or in Python terminology: A string. A string is a character, word, or sentence that you might want to store or display to a screen.

The input() function just shows the message Enter a number: to the screen, waits for the user to input something and then stores it in the user_input variable.

We would need 3 inputs: The first number, second number, and what operation to perform on them:

x = input('Enter a number: ')
y = input('Enter another number: ')
operation = input('Enter an operation (+, -, *, /): ')

A slight problem

There is a slight problem with this though. To add two numbers in python we just put the + between them. So, if we ignore the operation variable and just show the sum of the two numbers, we will simply type:

x = input('Enter a number: ')
y = input('Enter another number: ')
print(x+y)

If you actually run this, you will find something very weird. Look at this example:

Running the program

Weird right? Instead of adding them, the computer sort of just puts them beside each other. Here’s when you need to know about Python Data Types. Since

Data Types in Python

Computers store everything as binary, it can’t tell the difference between the 1's and 0’s that point to the number 1, and the 1’s and 0’s that point to the word “One”. For the computer, both 1 and “One” are just 1’s and 0’s. To tell Python that no! 1 is different from “One”. 1 is a number that can be added and multiplied and so on, and “One” is a word in a sentence, you need to specify the data type. We’re going to talk about 3 main data types in Python: Strings, Integers, and Floats.

  • Strings are as I’ve explained them before: Characters, words, sentences, etc. Something like “Hello!”, “a”, etc.
  • Integers are the same integers that you’ve learnt in Math. These are numbers and we can perform arithmetic on them. Something like 10, -4, 3, etc
  • Floats are decimal numbers. They are called “Floats” because that’s how computers store them, but this is a complex concept so we will not talk about why they are called floats. Basically, things like 3.14, 0.3515, etc

Type Casting

Our problem is that the default type for variables that are inputted is string. So Python treats them like a word, not a number. So, when we use the + operation on two strings, python simply combines both the strings into one. We need to tell Python that these are numbers, not strings. We do this by something known as “Type Casting”. Type Casting is simply, telling Python that you want it to treat the variable as a particular data type.

We do as follows:

x = int(input('Enter a number: '))
y = int(input('Enter another number: '))

The int here is a short-form of “Integer”. Sorrounding the input with the int() is telling python that whatever input you get, treat it like its an integer number. Now our program will perform the right calculations for them.

Since the operation variable is not a number, we’re going to leave it as it is. It being a string is perfectly fine.

So, our code is this much till now:

x = int(input('Enter a number: '))
y = int(input('Enter another number: '))
operation = input('Enter an operation (+, -, *, /): ')

Calculator Logic and the Output

Now that we have the numbers and the operation to perform, let’s make a 4-function calculator. It can add, subtract, multiply, and divide the numbers.

Here we use if-elif-else statements. An if statements is just asking the computer a “yes or no” question. If the answer is “yes”, then do something, if the answer is “no”, then do something else.

Our operation can be of 4 types: +, -, *, / . We need to ask the computer the following quesitons: “If the operation is +, add them, else, if the operation is -, subtract them, else, if the operation is *…” and so on. We codify that sentence in Python as follows:

if (operation == '+'):
  print(x+y)
elif (operation == '-'):
  print(x-y)
elif (operation == '*'):
  print(x*y)
elif (operation == '/'):
  print(x/y)
else:
  print("I do not understand that operation")

Notice a few more things happening here. The first is this weird symbol: == . This double equals sign is to differentiate from the = single equals sign.

Difference between = and ==

When we were initializing the variables, we said something like

operation = input('Enter an operation')

This tells python that whatever is the value of the input, set operation to be that value. Now if we use the same symbol to check the value of operation, like:

operation = '+'

Python will get confused. It will be like “Should I set the value of operation to ‘+’ or am I checking whether or not the value of operation is ‘+’ or not.” To solve this confusion, we use different symbols. = tells python to set the value of the variable, and == tells python to check the value of the variable.

So, you should readif (operation == '+') as “If the value of the operation is +, then”. Whatever code is indented after the if statement would be run. So if the value of the operation is indeed ‘+’. then the variables will be added and then print the result to the display.

If that is not the case, i.e operation is not ‘+’ but something else, then we move on. We basically have to tell the computer this: “If operation is +, then do this, else, if the operation is =, then do this”. Python combines the “else, if” part into a single word: elif . And the logic continues.

Once we have checked for all 4 of the cases, we’re still not done. What if the user enters something bizzare for the operation variable like “?”. If the operation is not any of the defined operations, then you have to tell the user that something went wrong. Here’s when we use the final else block. This block means that if all of the above conditions failed, then run this code. And we just tell the user we don’t understand that operation.

Full Code

x = int(input('Enter a number: '))
y = int(input('Enter another number: '))
operation = input('Enter an operation (+, -, *, /): ')

if (operation == '+'):
  print(x+y)
elif (operation == '-'):
  print(x-y)
elif (operation == '*'):
  print(x*y)
elif (operation == '/'):
  print(x/y)
else:
  print("I do not understand that operation")

Conclusion

Congratulations! You’ve successfully created a simple calculator in Python. Keep practicing and exploring new concepts to further develop your Python skills. Though there are a few problems:

  • What if the user is naughty and enters alphabets instead of numbers to the calculator?
  • what if the user tries to divide 1 with 0?
  • How do we implement more complex functions like sin(x), log(x), etc?

We will dive into these features in later blogs, so stay tuned!

Feedback and Comments: If you have any questions or feedback about this tutorial, please leave a comment below. We’d love to hear from you and help in any way we can. Happy coding!